package com.foodcommunity.service.impl;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.LoginDTO;
import com.foodcommunity.dto.RegisterDTO;
import com.foodcommunity.dto.UpdateProfileDTO;
import com.foodcommunity.entity.User;
import com.foodcommunity.mapper.UserMapper;
import com.foodcommunity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<User> login(LoginDTO loginDTO) {
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            return Result.error("用户名不存在");
        }
        if (!user.getPassword().equals(loginDTO.getPassword())) {
            return Result.error("密码错误");
        }
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<User> register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (checkUsername(registerDTO.getUsername())) {
            return Result.error("用户名已存在");
        }

        // 检查两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return Result.error("两次输入的密码不一致");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        user.setNickname(registerDTO.getNickname());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insert(user);
        return Result.success(user);
    }

    @Override
    public boolean checkUsername(String username) {
        return userMapper.findByUsername(username) != null;
    }

    @Override
    public Result<User> getUserInfo(Long id) {
        User user = userMapper.findById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<User> updateProfile(Long userId, UpdateProfileDTO profileDTO) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 更新基本信息
        user.setNickname(profileDTO.getNickname());
        user.setBio(profileDTO.getBio());
        
        // 更新美食偏好和烹饪技能
        String foodPreference = profileDTO.getFoodPreference();
        String cookingSkill = profileDTO.getCookingSkill();
        
        // 如果传入空字符串，则设置为null
        user.setFoodPreference(foodPreference != null && !foodPreference.trim().isEmpty() ? foodPreference.trim() : null);
        user.setCookingSkill(cookingSkill != null && !cookingSkill.trim().isEmpty() ? cookingSkill.trim() : null);
        
        user.setUpdateTime(LocalDateTime.now());

        userMapper.update(user);
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<User> updateAvatar(Long userId, String avatarUrl) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        user.setAvatar(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());

        userMapper.update(user);
        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<User> updateBackground(Long userId, String backgroundUrl) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        user.setBackgroundImage(backgroundUrl);
        user.setUpdateTime(LocalDateTime.now());

        userMapper.update(user);
        return Result.success(user);
    }

    @Override
    public boolean updateUser(User user) {
        int result = userMapper.update(user);
        return result > 0;
    }
    
    @Override
    public Map<String, Object> getUserList(int page, int size, String keyword) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 查询用户列表
        List<User> users = userMapper.findUserList(offset, size, keyword);
        
        // 查询总用户数
        int total = userMapper.countUsers(keyword);
        
        // 计算总页数
        int totalPages = (total + size - 1) / size;
        
        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("users", users);
        result.put("totalPages", totalPages);
        result.put("total", total);
        
        return result;
    }
    
    @Override
    @Transactional
    public boolean deleteUser(Long userId) {
        // 查询用户是否存在
        User user = userMapper.findById(userId);
        if (user == null) {
            return false;
        }
        
        // 防止删除管理员账号
        if ("admin".equals(user.getUsername())) {
            return false;
        }
        
        // 删除用户
        return userMapper.deleteById(userId) > 0;
    }
}